using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TalkBoxCtrollor : MonoBehaviour
{
    public Text TalkBoxText;
    public Text Name;
    public string[] TextValue;
    public float ReadSpeed;
    public GameObject Next;
    public Image PortraitImage;

    private Sprite sprite;

    private int ReadIndex = 0;
    private bool Done = false;
    private string ReadMode;

    public void Start()
    {
        ReadSpeed = SystemCtrollor.TextReadSpeed;
        // Debug.Log(TextValue[0]);
        ReadString(TextValue[0]);
    }

    public void Update()
    {
        if(Done){
            Next.SetActive(true);
        }
        if(Input.anyKeyDown && ReadIndex < (TextValue.Length - 1) && Done){
            ReadIndex ++;
            ReadString(TextValue[ReadIndex]);
        }
    }
    void ResetTalkBox(){
        TalkBoxText.text = "";
        Next.SetActive(false);
        Done = false;
    }

    void ReadString(string Read){
        ReadMode = "RN";
        Name.text = "";
        string Texts = "";
        string ImageIndex = "";
        for(int i = 0;i < Read.Length;i++){
            if(ReadMode == "RN"){
                if(Read[i] != ';'){
                    Name.text += Read[i];
                }
                else{
                    ReadMode = "RI";
                    continue;
                }
            }
            else if(ReadMode == "RI"){
                if(Read[i] != ';'){
                    ImageIndex += Read[i];
                }
                else{
                    ReadMode = "RT";
                    string Path = "PortraitImages/" + ImageIndex;
                    sprite = Resources.Load(Path,typeof(Sprite)) as Sprite;
                    PortraitImage.sprite = sprite;
                    continue;
                }
            }
            else{
                Texts += Read[i];
            }
        }
        ResetTalkBox();
        StartCoroutine(Readder(ReadSpeed,Texts));
    }
    IEnumerator Readder(float Speed,string InputString){
        for(int r = 0;r < InputString.Length;r ++){
            TalkBoxText.text += InputString[r].ToString();
            yield return new WaitForSeconds(Speed);
        }
        Done = true;
    }
}
